package com.bamboo.tool.util;

import com.intellij.psi.*;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;

public class PsiAnnotationMemberUtil {


    @SneakyThrows
    public static List<String> oneExpression(PsiAnnotationMemberValue value) {
        List<String> values = new ArrayList<>();
        if (value instanceof PsiLiteralExpression) {
            PsiLiteralExpression literal = (PsiLiteralExpression) value;
            values.add(literal.getValue().toString());
        } else if (value instanceof PsiClassObjectAccessExpression) {
            PsiClassObjectAccessExpression classObject = (PsiClassObjectAccessExpression) value;
            values.add(classObject.getOperand().getType().getPresentableText());
        } else if (value instanceof PsiReferenceExpression) {
            PsiReferenceExpression reference = (PsiReferenceExpression) value;
            PsiElement resolve = reference.resolve();
            if (resolve instanceof PsiField) {
                PsiField field = (PsiField) resolve;
                if (field != null && field.getInitializer() != null) {
                    List<String> fields = oneExpression(field.getInitializer());
                    values.addAll(fields);
                }else if(field != null &&field.getInitializer() == null){
                    values.add(field.getName());
                }
            } else {
                values.add(reference.getReferenceName());
            }

        } else if (value instanceof PsiArrayInitializerMemberValue) {
            PsiArrayInitializerMemberValue arrayInitializerMemberValue = (PsiArrayInitializerMemberValue) value;
            PsiAnnotationMemberValue[] initializers = arrayInitializerMemberValue.getInitializers();
            for (PsiAnnotationMemberValue initializer : initializers) {
                List<String> strings = oneExpression(initializer);
                values.addAll(strings);
            }
        } else if (value instanceof PsiPolyadicExpression) {
            PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression) value;
            PsiExpression[] operands = polyadicExpression.getOperands();
            String str = "";
            for (PsiExpression operand : operands) {
                List<String> strings = oneExpression(operand);
                if (strings.size() > 0) {
                    str = str + strings.get(0);
                }
            }
            values.add(str);

        }else {
            System.out.printf("");
        }
        return values;
    }
}
